import React, { useState, useEffect } from "react";
import { message } from "antd";

import "antd/dist/antd.css";

import {
  storeFontInfo,
  getStoredFontInfo,
  getBorderStatus,
  storeBorderStatus,
} from "@utils";

import Configs from "@config";

import { getFontList as getFontListApi } from "@api";

import Popup from "@popup/components";

import QR from "./shirkhan-qr.jpg";

const fontConfig = Configs.font;

const pageLimit = 10;

function getFontList(fontdata) {
  return (
    Object.keys(fontdata).map((key) => {
      const font = fontdata[key];
      return {
        ...font,
        name: font.nameing_table.fullName.en,
      };
    }) || []
  );
}

function orderFontList(fontlist = []) {
  const checkedFont = fontlist.filter((item) => item.checked);
  const otherFonts = fontlist.filter((item) => !item.checked);
  return checkedFont.concat(otherFonts);
}

const App = (props) => {
  const { header } = props;
  const [loading, setLoading] = useState(true);
  const [pageSize, setPageSize] = useState(1);
  const [borderStatus, setBorderStatus] = useState(true);
  const [storedFontName, setStoredFontName] = useState("UKIJ Tuz Kitab");
  const [fontData, setFontData] = useState({});
  const [fontList, setFontList] = useState([]);

  useEffect(() => {
    //获取字体列表
    getFontListApi()
      .then((response) => {
        if (response.status !== 200) {
          message.error({
            content: "获取字体列表时失败,状态码非200",
          });
          console.log(response);
        }

        //如果成功
        const fontdata = response.data.data;
        let fontlist = getFontList(fontdata);

        //读取本地store过的字体信息，做一个默认check
        getStoredFontInfo(function ({ fontinfo }) {
          fontlist = fontlist.map((item) => {
            if (item.name === fontinfo.name) {
              item.checked = true;
            } else {
              item.checked = false;
            }
            return item;
          });

          fontlist = orderFontList(fontlist);

          setFontData(fontdata);
          setFontList(fontlist);
          setLoading(false);
        });
      })
      .catch((err) => {
        message.error({
          content: "网路请求错误",
        });
        console.log(err);
      });
  }, []);

  useEffect(() => {
    //初始化 字体和border状态
    getStoredFontInfo(function ({ fontinfo }) {
      setStoredFontName(fontinfo.name);
    });

    getBorderStatus(function ({ border_status }) {
      setBorderStatus(border_status);
    });
  }, []);

  useEffect(() => {
    //border状态更新同步到store
    storeBorderStatus(borderStatus);
  }, [borderStatus]);

  function handleMore(e) {
    const maxPage = Math.round((Object.keys(fontData).length + 2) / pageLimit);
    if (pageSize > maxPage) {
      message.warning({
        content: "ئەمدى قالمىدى",
      });
      return;
    }
    setLoading(true);
    setTimeout(() => {
      setPageSize((size) => size + 1);
      setLoading(false);
    }, 300);
  }

  function handleDownload(fontName) {
    const fontInfo = fontList.filter((item) => item.name === fontName);
    const url =
      fontInfo.length > 0 ? fontConfig.fonts_url + fontInfo[0]["ttf"] : "";

    const options = {
      url,
      filename: `${fontName}.ttf`,
      saveAs: true,
    };
    setLoading(true);
    chrome.downloads.download(options, (res) => {
      setLoading(false);
    });
    // chrome.tabs.create({
    //   url: url,
    // });
  }

  function handleFontChange(fontName) {
    setLoading(true);

    let fontlist = fontList.map((font) => {
      if (font.name === fontName) {
        font.checked = true;
      } else {
        font.checked = false;
      }
      return font;
    });

    fontlist = orderFontList(fontlist);

    const fontinfo = fontList.filter((item) => {
      return fontName === item.name;
    });

    if (fontinfo.length > 0) {
      //保存在store中
      storeFontInfo(fontinfo[0], function (...params) {
        message.success({
          content: "بەتنى يىڭىلىغاندىن كېيىن كۈچكە ئىگە بولىدۇ",
          onClose: () => {
            setLoading(false);
            setFontList(fontlist);
            //让fontlist 区域滚回到顶部
            document.getElementsByClassName("fontlist_tab")[0].scrollTo(0, 0);
          },
        });
      });
    }
  }

  function onSearch(value) {
    let fontlist = [];

    if (value.length > 0) {
      fontlist = fontList.filter(({ name }) => {
        return (
          name.toLocaleLowerCase().indexOf(value.toLocaleLowerCase()) !== -1
        );
      });
    } else {
      setPageSize(1);
      //读取本地store过的字体信息，做一个默认check
      fontlist = getFontList(fontData);
    }

    fontlist = fontlist.map((item) => {
      item.checked = item.name === storedFontName ? true : false;
      return item;
    });
    fontlist = orderFontList(fontlist);
    setFontList(fontlist);
  }

  function handleSwitchChange(checked) {
    message.success({
      content: "بەتنى يىڭىلىغاندىن كېيىن كۈچكە ئىگە بولىدۇ",
    });
    setBorderStatus(checked);
  }

  return (
    <Popup
      header={header}
      fontlist={fontList.slice(0, pageSize * pageLimit)}
      loading={loading}
      onLoadMore={handleMore}
      onDownloadClick={handleDownload}
      onFontChange={handleFontChange}
      onSearch={onSearch}
      onSwitchChange={handleSwitchChange}
      bordered={borderStatus}
      qr={QR}
    />
  );
};

export default App;
